const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");

const app = new Koa();
const router = new Router();
const pupp = require("./pupp");

router.get("/", async (ctx) => {
  ctx.body = {
    version: "1.0.1",
  };
});

router.get("/pupp", async (ctx) => {
  const data = await pupp.getData(ctx.query);
  ctx.body = data;
});

// 捕获错误，返回500状态和提示
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    if (pupp.inLocal) console.log(err);
    ctx.status = err.statusCode || err.status || 500;
    ctx.body = {
      msg: err.message || err,
    };
  }
});

app.use(bodyParser()).use(router.routes()).use(router.allowedMethods());
// .use(Cors()) // 本地跨域调试

const port = process.env.PORT || 80;
app.listen(port, () => {
  console.log(`start on http://localhost:` + port);
});
